﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DbHelp;
using System.IO;
using DevExpress.XtraTreeList.Nodes;
using System.Diagnostics;
using ICommon;
using System.Threading;
using System.Collections;

namespace IotherRis
{
    public partial class Fr_main_other : DevExpress.XtraEditors.XtraForm
    {
        #region 属性
        string[] mOtherParams;

        public string[] MOtherParams
        {
            get { return mOtherParams; }
            set { mOtherParams = value; }
        }
        DevExpress.XtraReports.UI.XtraReport mReport;

        Hashtable mAllPtintTemplate = new Hashtable();

        Model_cfg mModel_cfg = null;

        #endregion



        #region  全局参数
        uDataSetC mDs_P_Load = null;
        uDataSetC mDs_R_Load = null;
        DataView mDv_Template = null;

        uDataSetC mUds_click = null;

        string mAccess_no = "";
        string mPiVewmColum = "";

        RichTextBox mPrintDesc = new RichTextBox();
        RichTextBox mPrintDiag = new RichTextBox();
        int mMaxReportKey = 0;

        TreeListNode mDeletNode = null;
        #endregion
        public Fr_main_other()
        {
            InitializeComponent();

        }



        public void f_reload_params(string[] pParams)
        {
            //Program.T.Start((object)this);

            for (int i = 1; i < pParams.Length; i++)
            {
                this.Text = this.Text + pParams[i] + "| ";
            }
            mOtherParams = null;
            mOtherParams = pParams;



            if (mOtherParams != null)
            {
                if (mOtherParams.Length > 0)
                {
                    //选中报告书写界面
                    tab_pages.SelectedTabPage = tabPage_report;
                    f_tabPages_report_reload(mOtherParams);
                }

            }

        }

        public Fr_main_other(string[] pParams)
        {
            InitializeComponent();

            for (int i = 1; i < pParams.Length; i++)
            {
                this.Text = this.Text + pParams[i] + "| ";
            }
            mOtherParams = null;
            mOtherParams = pParams;
            Control.CheckForIllegalCrossThreadCalls = false;//关闭跨线程调用检测
        }

        private void Fr_main_other_Load(object sender, EventArgs e)
        {
            ////MessageBox.Show(mPiewDb);
            mPiVewmColum = AccessHelper.IniReadValue("SERVER", "PIVIEW_COLUMNE", Environment.CurrentDirectory + @"\sysconfig.ini");

            if (string.IsNullOrEmpty(mPiVewmColum))
            {

                AccessHelper.IniWriteValue("SERVER", "PIVIEW_COLUMNE", "PATIENT_ID", Environment.CurrentDirectory + @"\sysconfig.ini");
                mPiVewmColum = "PATIENT_ID";
            }

            //加载报告模版
            f_loadAllTemplate();

            //加载打印模版名称

            f_loadPrintTemplate();

            //加载基本信息
            f_loadBaseInfo();

            f_loadIniCfg();

            //MessageBox.Show(mReportDb);
            if (mOtherParams != null)
            {
                if (mOtherParams.Length > 0)
                {
                    //选中报告书写界面
                    tab_pages.SelectedTabPage = tabPage_report;
                    f_tabPages_report(mOtherParams);
                }
            }




        }






        private void g3ButtonA1_Click(object sender, EventArgs e)
        {
            //查询access  ds
            string mSql = "select * from study ";
            uDataSetC mxx = new uDataSetC(mSql);

            mxx.SetItem(1, "AETITLE", "1111");
            mxx.Update();
        }



        #region 方法
        /// <summary>
        /// 通过传入的信息查新PIVIEW数据库,加载病人信息
        /// </summary>
        /// <param name="mOtherParams"></param>
        public void f_tabPages_report(string[] mOtherParams)
        {
            if (tab_pages.SelectedTabPage != tabPage_report)
            {
                tab_pages.SelectedTabPage = tabPage_report;
            }

            try
            {


                //PIVIEW study 表 study_key,patient_id,patient_name,patient_sex,patient_birth_date,patient_age,study_instance_uid,study_id,study_dttm,access_no
                //study_desc,refer_doctor,read_doctor,series_count,instance_count,modality,bodypart,report_key,userdef1,userdef2,AETitle,Institution,modality
                f_clear_report_face();

                if (mOtherParams.Length < 1)
                {
                    MessageBox.Show("传入参数不能为空,请检查系统配置");
                    return;
                }
                string mP_param_value = mOtherParams[0];

                string mSQL_P_Load = "select * from study where  study_instance_uid='" + mP_param_value + "'";
                mDs_P_Load = null;
                mDs_P_Load = new uDataSetC(mSQL_P_Load, AccessHelper.mPiewDb);

                string mSQL_R_Load = "select * from PI_REPORT where  study_uid='" + mP_param_value + "'";
                mDs_R_Load = null;
                mDs_R_Load = new uDataSetC(mSQL_R_Load, AccessHelper.mReportDb);
                if (mDs_P_Load.RowCount() > 1)
                {
                    MessageBox.Show("PACS中STUDY_INSTANCE_UID值不唯一，请联系管理员");
                }
                if (mDs_P_Load.RowCount() < 1)
                {
                    MessageBox.Show("没有查询到检查信息");
                    return;
                }

                if (mDs_R_Load.RowCount() < 1)
                {
                    if (mDs_P_Load.RowCount() == 1)
                    {
                        //从study表中加载已有病人信息
                        txt_r_age.Text = mDs_P_Load.GetItemString(1, "patient_age");
                        txt_r_patientID.Text = mDs_P_Load.GetItemString(1, "patient_id");
                        string mSex = mDs_P_Load.GetItemString(1, "patient_sex");
                        if (mSex.ToUpper() == "M")
                        {
                            txt_r_sex.Text = "男";
                        }
                        else if (mSex == "F")
                        {

                            txt_r_sex.Text = "女";

                        }
                        else
                        {
                            txt_r_sex.Text = "未知";
                        }

                        txt_r_study_dttm.Text = mDs_P_Load.GetItemString(1, "study_dttm");
                        txt_r_name.Text = mDs_P_Load.GetItemString(1, "patient_name");
                        txt_r_bodayprt.Text = mDs_P_Load.GetItemString(1, "bodypart");
                        txt_r_studyd_esc.Text = mDs_P_Load.GetItemString(1, "study_desc");
                        txt_template_modality.Text = "";
                        txt_template_modality.Text = mDs_P_Load.GetItemString(1, "modality");
                        mAccess_no = mDs_P_Load.GetItemString(1, "access_no");
                    }
                }
                else
                {
                    //从report表中加载病人信息+和报告信息
                    txt_r_age.Text = mDs_R_Load.GetItemString(1, "age");
                    txt_r_patientID.Text = mDs_R_Load.GetItemString(1, "patient_id");
                    txt_r_sex.Text = mDs_R_Load.GetItemString(1, "patient_sex");
                    txt_r_study_dttm.Text = mDs_R_Load.GetItemString(1, "study_dttm");
                    txt_r_name.Text = mDs_R_Load.GetItemString(1, "patient_name");
                    txt_r_bednum.Text = mDs_R_Load.GetItemString(1, "bed_number");
                    txt_r_refer_department.Text = mDs_R_Load.GetItemString(1, "request_department");
                    refer_doctor.Text = mDs_R_Load.GetItemString(1, "request_doctor");
                    mAccess_no = mDs_R_Load.GetItemString(1, "access_no");

                    txt_r_desc.Rtf = mDs_R_Load.GetItemString(1, "REPORT_DESC");
                    txt_r_Diagnose.Rtf = mDs_R_Load.GetItemString(1, "REPORT_DIAGNOSE");

                    txt_r_bodayprt.Text = mDs_R_Load.GetItemString(1, "bodypart");
                    txt_r_studyd_esc.Text = mDs_R_Load.GetItemString(1, "study_desc");

                    txt_r_Inpatient_id.Text = mDs_R_Load.GetItemString(1, "INPATIENT_ID");
                    txt_r_outpatient_id.Text = mDs_R_Load.GetItemString(1, "OUTPATIENT_ID");
                    txt_r_space.Text = mDs_R_Load.GetItemString(1, "EXAM_SPACE");
                    txt_r_thickness.Text = mDs_R_Load.GetItemString(1, "EXAM_THICKNESS");
                    txt_r_method.Text = mDs_R_Load.GetItemString(1, "EXAM_METHOD");

                    txt_r_report_doctor.Text = mDs_R_Load.GetItemString(1, "REPORT_DOCTOR");


                    txt_r_approval_doctor.Text = mDs_R_Load.GetItemString(1, "APPROVAL_DOCTOR");
                    txt_template_modality.Text = "";
                    txt_template_modality.Text = mDs_R_Load.GetItemString(1, "modality");

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询失败" + ex.Message);
            }


        }


        /// <summary>
        /// 通过传入的信息查新PIVIEW数据库,加载病人信息
        /// </summary>
        /// <param name="mOtherParams"></param>
        public void f_tabPages_report_reload(string[] mOtherParams)
        {
            try
            {
                //MessageBox.Show("再次加载了");
                //txt_r_age.Text = "33333333333333333333333";
                //PIVIEW study 表 study_key,patient_id,patient_name,patient_sex,patient_birth_date,patient_age,study_instance_uid,study_id,study_dttm,access_no
                //study_desc,refer_doctor,read_doctor,series_count,instance_count,modality,bodypart,report_key,userdef1,userdef2,AETitle,Institution,modality
                if (mOtherParams.Length < 1)
                {
                    MessageBox.Show("传入参数不能为空,请检查系统配置");
                    return;
                }
                string mP_param_value = mOtherParams[0];
                // MessageBox.Show("再次查询" + mP_param_value);
                string mSQL_P_Load = "select * from study where  study_instance_uid='" + mP_param_value + "'";
                mDs_P_Load = null;
                mDs_P_Load = new uDataSetC(mSQL_P_Load, AccessHelper.mPiewDb);

                //  MessageBox.Show(mDs_P_Load.GetItemString(1, "study_instance_uid"))
                ;
                //t.Start((object)this);
                // Program.T.Start((object)this);

                string mSQL_R_Load = "select * from PI_REPORT where  study_uid='" + mP_param_value + "'";
                mDs_R_Load = null;
                mDs_R_Load = new uDataSetC(mSQL_R_Load, AccessHelper.mReportDb);
                if (mDs_P_Load.RowCount() > 1)
                {
                    MessageBox.Show("PACS中STUDY_INSTANCE_UID值不唯一，请联系管理员");
                }
                if (mDs_P_Load.RowCount() < 1)
                {
                    MessageBox.Show("没有查询到检查信息");
                    return;
                }

                if (mDs_R_Load.RowCount() < 1)
                {
                    if (mDs_P_Load.RowCount() == 1)
                    {
                        // MessageBox.Show("再次查询" + "开始赋值1" + mDs_P_Load.GetItemString(1, "patient_age"));
                        //从study表中加载已有病人信息




                        //异步方式更新界面






                        txt_r_age.Text = "33333333333333333333333";
                        //txt_r_age.Text = mDs_P_Load.GetItemString(1, "patient_age");
                        txt_r_patientID.Text = mDs_P_Load.GetItemString(1, "patient_id");
                        string mSex = mDs_P_Load.GetItemString(1, "patient_sex");
                        if (mSex.ToUpper() == "M")
                        {
                            txt_r_sex.Text = "男";
                        }
                        else if (mSex == "F")
                        {

                            txt_r_sex.Text = "女";

                        }
                        else
                        {
                            txt_r_sex.Text = "未知";
                        }

                        txt_r_study_dttm.Text = mDs_P_Load.GetItemString(1, "study_dttm");
                        txt_r_name.Text = mDs_P_Load.GetItemString(1, "patient_name");
                        txt_r_bodayprt.Text = mDs_P_Load.GetItemString(1, "bodypart");
                        txt_r_studyd_esc.Text = mDs_P_Load.GetItemString(1, "study_desc");

                    }
                }
                else
                {
                    //从report表中加载病人信息+和报告信息
                    // MessageBox.Show("再次查询" + "开始赋值2"+mDs_R_Load.GetItemString(1, "age"));
                    txt_r_age.Text = "444444444444444444444";
                    // txt_r_age.Text = mDs_R_Load.GetItemString(1, "age");
                    txt_r_patientID.Text = mDs_R_Load.GetItemString(1, "patient_id");
                    txt_r_sex.Text = mDs_R_Load.GetItemString(1, "patient_sex");
                    txt_r_study_dttm.Text = mDs_R_Load.GetItemString(1, "study_dttm");
                    txt_r_name.Text = mDs_R_Load.GetItemString(1, "patient_name");
                    txt_r_bednum.Text = mDs_R_Load.GetItemString(1, "bed_number");
                    txt_r_refer_department.Text = mDs_R_Load.GetItemString(1, "request_department");
                    refer_doctor.Text = mDs_R_Load.GetItemString(1, "request_doctor");


                    txt_r_desc.Text = mDs_R_Load.GetItemString(1, "REPORT_DESC");
                    txt_r_Diagnose.Text = mDs_R_Load.GetItemString(1, "REPORT_DIAGNOSE");

                    txt_r_bodayprt.Text = mDs_R_Load.GetItemString(1, "bodypart");
                    txt_r_studyd_esc.Text = mDs_R_Load.GetItemString(1, "study_desc");

                    txt_r_Inpatient_id.Text = mDs_R_Load.GetItemString(1, "INPATIENT_ID");
                    txt_r_outpatient_id.Text = mDs_R_Load.GetItemString(1, "OUTPATIENT_ID");
                    txt_r_space.Text = mDs_R_Load.GetItemString(1, "EXAM_SPACE");
                    txt_r_thickness.Text = mDs_R_Load.GetItemString(1, "EXAM_THICKNESS");
                    txt_r_method.Text = mDs_R_Load.GetItemString(1, "EXAM_METHOD");

                    txt_r_report_doctor.Text = mDs_R_Load.GetItemString(1, "REPORT_DOCTOR");


                    txt_r_approval_doctor.Text = mDs_R_Load.GetItemString(1, "APPROVAL_DOCTOR");

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询失败" + ex.Message);
            }


        }
        public void f_Print(uDataSetC mPrintDs, string mPrintTemplateName)
        {

            if (mPrintDs == null)
            {
                MessageBox.Show("没有报告数据,不能预览或打印");
                return;
            }
            //
            if (!mAllPtintTemplate.ContainsKey(mPrintTemplateName))
            {
                uDataSetC mDataDs_add = new uDataSetC(@" select * from PI_PRINTTEMPLATE where TEMPLATE_NAME ='" + mPrintTemplateName + "'", AccessHelper.mReportDb);
                mAllPtintTemplate.Add(mPrintTemplateName, mDataDs_add);
            }

            uDataSetC mDataDs = (uDataSetC)mAllPtintTemplate[mPrintTemplateName];
            if (mDataDs.RowCount() > 0)
            {
                byte[] SMbStr = mDataDs.GetItemByte(1, "TEMPLATE_CONTNET");
                string mSql = AccessHelper.f_ByteToStr(mDataDs.GetItemByte(1, "TEMPLATE_SQL"));
                //获取打印数据
                Stream sr = new MemoryStream(SMbStr);
                if (mReport == null)
                {
                    mReport = new DevExpress.XtraReports.UI.XtraReport();
                }

                mReport.LoadLayout(sr);
                if (mPrintDs.RowCount() > 0)
                {

                    //再次加载打印数据
                    string mStudy_uid = mPrintDs.GetItemString(1, "study_uid");
                    mSql = mSql + " '" + mStudy_uid + "'";
                    uDataSetC mTruePrint = new uDataSetC(mSql, AccessHelper.mReportDb);

                    //设置打印样式和字体

                    mPrintDesc.Rtf = mTruePrint.GetItemString(1, "报告内容");

                    mPrintDiag.Rtf = mTruePrint.GetItemString(1, "报告诊断");

                    try
                    {
                        mPrintDesc.Font = new Font(mModel_cfg.MPrint_font, (float)Convert.ToDouble(mModel_cfg.MPrint_font_size));
                        mPrintDiag.Font = new Font(mModel_cfg.MPrint_font, (float)Convert.ToDouble(mModel_cfg.MPrint_font_size));
                    }
                    catch
                    {
                        mPrintDesc.Font = new Font("宋体", 12);
                        mPrintDiag.Font = new Font("宋体", 12);
                    }

                    mTruePrint.SetItem(1, "报告内容", f_Replace_Space(mPrintDesc));
                    mTruePrint.SetItem(1, "报告诊断", f_Replace_Space(mPrintDiag));

                    mReport.DataSource = mTruePrint;


                    printControl1.PrintingSystem = mReport.PrintingSystem;


                    mReport.CreateDocument();


                    //组织打印信息

                    if (printingSystem1 == null)
                    {
                        printingSystem1 = new DevExpress.XtraPrinting.PrintingSystem();

                    }

                    if (!(printControl1 == null))
                    {
                        printControl1.PrintingSystem = printingSystem1;
                        mReport.PrintingSystem = printingSystem1;
                        mReport.CreateDocument();
                    }
                }
            }
        }

        public void f_loadAllTemplate()
        {



            string mSql_load = @"select * from PI_REPORTTEMPLATE";
            uDataSetC mDs_AllTem = new uDataSetC(mSql_load, AccessHelper.mReportDb);
            mDv_Template = new DataView();
            mDv_Template.Table = mDs_AllTem.Tables[0];

            //DataTable mDt = new DataTable();
            //DataColumn MdC1 = new DataColumn();
            //MdC1.DataType = System.Type.GetType("System.String");
            //MdC1.ColumnName = "IID";
            //mDt.Columns.Add(MdC1);

            //DataColumn MdC2 = new DataColumn();
            //MdC2.DataType = System.Type.GetType("System.String");
            //MdC2.ColumnName = "IPID";
            //mDt.Columns.Add(MdC2);

            //DataColumn MdC3 = new DataColumn();
            //MdC3.DataType = System.Type.GetType("System.String");
            //MdC3.ColumnName = "FFF";
            //mDt.Columns.Add(MdC3);

            //DataRow xx = mDt.NewRow();
            //xx["IID"] = 1;
            //xx["IPID"] = 0;
            //xx["FFF"] = "FERFERFWF";
            //mDt.Rows.Add(xx);

            //DataRow xx1 = mDt.NewRow();
            //xx1["IID"] = 2;
            //xx1["IPID"] = 1;
            //xx1["FFF"] = "FERFERFWF2222";
            //mDt.Rows.Add(xx1);

            tree_template.KeyFieldName = "IID";
            tree_template.ParentFieldName = "IPID";
            tree_template.DataSource = mDv_Template;

        }

        public void f_loadPrintTemplate()
        {

            string mSql_load = @"select * from pi_printtemplate where state<>'已删除'";
            uDataSetC mDs_AllPrint = new uDataSetC(mSql_load, AccessHelper.mReportDb);
            mAllPtintTemplate.Clear();

            for (int i = 1; i <= mDs_AllPrint.RowCount(); i++)
            {
                txt_r_printName.Properties.Items.Add(mDs_AllPrint.GetItemString(i, "TEMPLATE_NAME"));

            }
            txt_r_printName.SelectedIndex = 0;

        }

        private string f_Replace_Space(RichTextBox pRtb)
        {
            //空格按下的时候处理
            Int32 mPosition = -1;
            do
            {
                mPosition = pRtb.Find(new char[] { ' ' });
                if (mPosition >= 0)
                {
                    pRtb.SelectionStart = mPosition;
                    pRtb.SelectionLength = 1;
                    pRtb.SelectedText = "　";
                }
            } while (mPosition >= 0);

            return pRtb.Rtf;
        }

        private string f_Replace_Space(string pStr)
        {
            pStr.Replace(' ', '　');
            return pStr;
        }

        public void f_loadBaseInfo()
        {

            string mSql_load_tickness = @"select * from pi_baseinfo where cparamtype='层厚' and ipid<>0";
            uDataSetC mDs_tickness = new uDataSetC(mSql_load_tickness, AccessHelper.mReportDb);

            string mSql_load_space = @"select * from pi_baseinfo where cparamtype='层间距' and ipid<>0";
            uDataSetC mDs_space = new uDataSetC(mSql_load_space, AccessHelper.mReportDb);

            string mSql_load_users = @"select * from pi_baseinfo where cparamtype='人员信息' and ipid<>0";
            uDataSetC mDs_users = new uDataSetC(mSql_load_users, AccessHelper.mReportDb);

            string mSql_load_modlatys = @"select * from pi_baseinfo where cparamtype='设备类型' and ipid<>0";
            uDataSetC mDs_modlaitys = new uDataSetC(mSql_load_modlatys, AccessHelper.mReportDb);

            string mSql_load_method = @"select * from pi_baseinfo where cparamtype='检查方法' and ipid<>0";
            uDataSetC mDs_method = new uDataSetC(mSql_load_method, AccessHelper.mReportDb);


            txt_r_thickness.Properties.Items.Clear();

            for (int i = 1; i <= mDs_tickness.RowCount(); i++)
            {
                txt_r_thickness.Properties.Items.Add(mDs_tickness.GetItemString(i, "CPARAMCODE"));

            }

            txt_r_space.Properties.Items.Clear();

            for (int i = 1; i <= mDs_space.RowCount(); i++)
            {
                txt_r_space.Properties.Items.Add(mDs_space.GetItemString(i, "CPARAMCODE"));

            }

            txt_r_method.Properties.Items.Clear();

            for (int i = 1; i <= mDs_method.RowCount(); i++)
            {
                txt_r_method.Properties.Items.Add(mDs_method.GetItemString(i, "CPARAMCODE"));

            }

            txt_template_modality.Properties.Items.Clear();
            txt_template_modality.Properties.Items.Add("所有");

            for (int i = 1; i <= mDs_modlaitys.RowCount(); i++)
            {
                txt_template_modality.Properties.Items.Add(mDs_modlaitys.GetItemString(i, "CPARAMCODE"));
            }

            txt_r_approval_doctor.Properties.Items.Clear();

            txt_r_report_doctor.Properties.Items.Clear();
            for (int i = 1; i <= mDs_users.RowCount(); i++)
            {
                txt_r_approval_doctor.Properties.Items.Add(mDs_users.GetItemString(i, "CPARAMCODE"));
                txt_r_report_doctor.Properties.Items.Add(mDs_users.GetItemString(i, "CPARAMCODE"));

            }

            txt_q_report_doctor.Properties.Items.Clear();

            for (int i = 1; i <= mDs_users.RowCount(); i++)
            {
                txt_q_report_doctor.Properties.Items.Add(mDs_users.GetItemString(i, "CPARAMCODE"));

            }
        }


        public void f_loadIniCfg()
        {

            mModel_cfg = new Model_cfg();
            //加载INI配置信息
            //调用的列名

        }
        public void f_loadIniCfg(Model_cfg pModel_cfg)
        {
            f_loadIniCfg();
            // MessageBox.Show(mModel_cfg.MTrue_arges);
            try
            {
                txt_r_desc.Font = new Font(pModel_cfg.MReport_font, (float)Convert.ToDouble(pModel_cfg.MReport_font_size));
                txt_r_Diagnose.Font = new Font(pModel_cfg.MReport_font, (float)Convert.ToDouble(pModel_cfg.MReport_font_size));

                txt_r_desc.SelectionFont = new Font(pModel_cfg.MReport_font, (float)Convert.ToDouble(pModel_cfg.MReport_font_size));
                txt_r_Diagnose.SelectionFont = new Font(pModel_cfg.MReport_font, (float)Convert.ToDouble(pModel_cfg.MReport_font_size));
            }
            catch
            {
                txt_r_desc.Font = new Font("宋体", 12);
                txt_r_Diagnose.Font = new Font("宋体", 12);
                txt_r_desc.SelectionFont = new Font("宋体", 12);
                txt_r_Diagnose.SelectionFont = new Font("宋体", 12);
            }

            try
            {
                mPrintDesc.Font = new Font(pModel_cfg.MPrint_font, (float)Convert.ToDouble(pModel_cfg.MPrint_font_size));
                mPrintDiag.Font = new Font(pModel_cfg.MPrint_font, (float)Convert.ToDouble(pModel_cfg.MPrint_font_size));

                mPrintDesc.SelectionFont = new Font(pModel_cfg.MPrint_font, (float)Convert.ToDouble(pModel_cfg.MPrint_font_size));
                mPrintDesc.SelectionFont = new Font(pModel_cfg.MPrint_font, (float)Convert.ToDouble(pModel_cfg.MPrint_font_size));
            }
            catch
            {
                mPrintDesc.Font = new Font("宋体", 12);
                mPrintDiag.Font = new Font("宋体", 12);
                mPrintDesc.SelectionFont = new Font("宋体", 12);
                mPrintDesc.SelectionFont = new Font("宋体", 12);
            }

            //更新数据库路径 
            AccessHelper.mPiewDb = pModel_cfg.MDbpath;
            AccessHelper.mReportDb = pModel_cfg.MDbpath_report;

        }


        public void f_clear_report_face()
        {
            txt_r_age.Text = "";
            txt_r_patientID.Text = "";
            txt_r_sex.Text = "";
            txt_r_study_dttm.Text = "";
            txt_r_name.Text = "";
            txt_r_bednum.Text = "";
            txt_r_refer_department.Text = "";
            refer_doctor.Text = "";


            txt_r_desc.Text = "";
            txt_r_Diagnose.Text = "";

            txt_r_bodayprt.Text = "";
            txt_r_studyd_esc.Text = "";

            txt_r_Inpatient_id.Text = "";
            txt_r_outpatient_id.Text = "";
            txt_r_space.Text = "";
            txt_r_thickness.Text = "";
            txt_r_method.Text = "";

            txt_r_report_doctor.Text = "";


            txt_r_approval_doctor.Text = "";

            mAccess_no = "";
        }

        static char[] mTempChars;

        protected static char[] GetTempData()
        {
            if (mTempChars == null)
                mTempChars = new char[1024 * 64];
            return mTempChars;
        }

        public static string ReplaceNew(string value, string oldData, string newData)
        {
            char[] tmpchars = GetTempData();
            int newpostion = 0;
            int oldpostion = 0;
            int length = value.Length;
            int oldlength = oldData.Length;
            int newlength = newData.Length;
            int index = 0;
            int copylength = 0;
            bool eq = false;
            while (index < value.Length)
            {
                eq = true;
                for (int k = 0; k < oldlength; k++)
                {
                    if (value[index + k] != oldData[k])
                    {
                        eq = false;
                        break;
                    }

                }
                if (eq)
                {
                    copylength = index - oldpostion;
                    value.CopyTo(oldpostion, tmpchars, newpostion, copylength);
                    newpostion += copylength;
                    index += oldlength;
                    oldpostion = index;
                    newData.CopyTo(0, tmpchars, newpostion, newlength);
                    newpostion += newlength;

                }
                else
                {
                    index++;
                }
            }
            if (oldpostion < length)
            {
                copylength = index - oldpostion;
                value.CopyTo(oldpostion, tmpchars, newpostion, copylength);
                newpostion += copylength;
            }
            return new string(tmpchars, 0, newpostion);
        }

        #region 报告右键菜单
        private void Menu_nr_Opening(object sender, CancelEventArgs e)
        {
            if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
            {

                mi_nr_paste.Enabled = true;
            }
            else
            {
                mi_nr_paste.Enabled = false;
            }

            if (txt_r_desc.SelectedRtf.Length > 0 || txt_r_Diagnose.SelectedRtf.Length > 0 || txt_template_desc.SelectedRtf.Length > 0 || txt_template_diagnose.SelectedRtf.Length > 0)
            {
                mi_nr_copy.Enabled = true;
                mi_nr_delete.Enabled = true;
                mi_nr_x.Enabled = true;
            }
            else
            {
                mi_nr_copy.Enabled = false;
                mi_nr_delete.Enabled = false;
                mi_nr_x.Enabled = false;
            }

            if (txt_r_desc.CanUndo == true || txt_r_Diagnose.CanUndo == true)
            {
                mi_nr_z.Enabled = true;
            }
            else
            {
                mi_nr_z.Enabled = false;
            }
        }

        private void mi_nr_copy_Click(object sender, EventArgs e)
        {
            if (txt_r_desc.Focused)
            {
                txt_r_desc.Copy();
            }
            else if (txt_r_Diagnose.Focused)
            {
                txt_r_Diagnose.Copy();
            }
        }

        private void mi_nr_x_Click(object sender, EventArgs e)
        {
            if (txt_r_Diagnose.Focused)
            {
                txt_r_Diagnose.Cut();
            }
            else if (txt_r_desc.Focused)
            {
                txt_r_desc.Cut();
            }
        }

        private void mi_nr_paste_Click(object sender, EventArgs e)
        {
            if (txt_r_desc.Focused)
            {
                txt_r_desc.Paste();
            }
            else if (txt_r_Diagnose.Focused)
            {
                txt_r_Diagnose.Paste();
            }
        }

        private void mi_nr_delete_Click(object sender, EventArgs e)
        {
            if (txt_r_desc.Focused)
            {
                txt_r_desc.SelectedRtf = "";
            }
            else if (txt_r_Diagnose.Focused)
            {
                txt_r_Diagnose.SelectedRtf = "";
            }
        }

        private void mi_nr_z_Click(object sender, EventArgs e)
        {
            if (txt_r_Diagnose.Focused)
            {
                txt_r_Diagnose.Undo();
            }
            else if (txt_r_desc.Focused)
            {
                txt_r_desc.Undo();
            }

        }
        #endregion


        #endregion

        private void btn_r_save_Click(object sender, EventArgs e)
        {
            if (mDs_R_Load == null)
            {
                MessageBox.Show("没有查询加载数据,不能保存");
                return;
            }
            if (mDs_R_Load.RowCount() < 1)
            {
                mDs_R_Load.InsertRow();
                mDs_R_Load.SetItem(1, "iid", System.DateTime.Now.ToString("yyyyMMddHHmmss"));
            }

            if (mDs_R_Load.RowCount() >= 1)
            {
                try
                {
                    //从report表中加载病人信息+和报告信息

                    mDs_R_Load.SetItem(1, "age", txt_r_age.Text);
                    mDs_R_Load.SetItem(1, "patient_id", txt_r_patientID.Text);
                    mDs_R_Load.SetItem(1, "patient_sex", txt_r_sex.Text);
                    mDs_R_Load.SetItem(1, "study_dttm", txt_r_study_dttm.Text);
                    mDs_R_Load.SetItem(1, "patient_name", txt_r_name.Text);
                    mDs_R_Load.SetItem(1, "bed_number", txt_r_bednum.Text);
                    mDs_R_Load.SetItem(1, "request_department", txt_r_refer_department.Text);
                    mDs_R_Load.SetItem(1, "request_doctor", string.IsNullOrEmpty(refer_doctor.Text) == true ? "-" : refer_doctor.Text);
                    mDs_R_Load.SetItem(1, "REPORT_DESC", f_Replace_Space(txt_r_desc));//string.IsNullOrEmpty(txt_r_desc.Rtf) == true ? "-" : txt_r_desc.Rtf);
                    mDs_R_Load.SetItem(1, "REPORT_DIAGNOSE", f_Replace_Space(txt_r_Diagnose));//string.IsNullOrEmpty(txt_r_Diagnose.Rtf) == true ? "-" : txt_r_Diagnose.Rtf);
                    mDs_R_Load.SetItem(1, "study_uid", mDs_P_Load.GetItemString(1, "study_instance_uid"));
                    mDs_R_Load.SetItem(1, "study_key", mDs_P_Load.GetItemString(1, "study_key"));
                    mDs_R_Load.SetItem(1, "study_id", mDs_P_Load.GetItemString(1, "study_id"));
                    mDs_R_Load.SetItem(1, "study_desc", string.IsNullOrEmpty(txt_r_studyd_esc.Text) == true ? "-" : txt_r_studyd_esc.Text);

                    mDs_R_Load.SetItem(1, "modality", mDs_P_Load.GetItemString(1, "modality"));
                    mDs_R_Load.SetItem(1, "bodypart", string.IsNullOrEmpty(txt_r_bodayprt.Text) == true ? "-" : txt_r_bodayprt.Text);

                    mDs_R_Load.SetItem(1, "INPATIENT_ID", string.IsNullOrEmpty(txt_r_Inpatient_id.Text) == true ? "-" : txt_r_Inpatient_id.Text);
                    mDs_R_Load.SetItem(1, "OUTPATIENT_ID", string.IsNullOrEmpty(txt_r_outpatient_id.Text) == true ? "-" : txt_r_outpatient_id.Text);
                    mDs_R_Load.SetItem(1, "EXAM_THICKNESS", string.IsNullOrEmpty(txt_r_thickness.Text) == true ? "-" : txt_r_thickness.Text);
                    mDs_R_Load.SetItem(1, "EXAM_SPACE", string.IsNullOrEmpty(txt_r_space.Text) == true ? "-" : txt_r_space.Text);
                    mDs_R_Load.SetItem(1, "EXAM_METHOD", string.IsNullOrEmpty(txt_r_method.Text) == true ? "-" : txt_r_method.Text);

                    mDs_R_Load.SetItem(1, "REPORT_STATE", "已书写");

                    mDs_R_Load.SetItem(1, "REPORT_DOCTOR", string.IsNullOrEmpty(txt_r_report_doctor.Text) == true ? "-" : txt_r_report_doctor.Text);
                    mDs_R_Load.SetItem(1, "REPORT_DATE", System.DateTime.Now.ToString());

                    mDs_R_Load.SetItem(1, "APPROVAL_DOCTOR", txt_r_approval_doctor.Text);

                    mDs_R_Load.SetItem(1, "ACCESS_NO", string.IsNullOrEmpty(mAccess_no) == true ? "-" : mAccess_no);
                    mDs_R_Load.Update(AccessHelper.mReportDb);
                    //将报告内容写入piview report表,并更新study报的report_key列
                    //reprot 表列值 report_code report_text report_offset dictator transcriber approver approval_dttm update_dttm
                    try
                    {
                        if (mModel_cfg.MReportToPiview == "1")
                        {
                            string mStudy_report_key = "0";
                            if (string.IsNullOrEmpty(mDs_R_Load.GetItemString(1, "STUDY_REPORT_KEY")))
                            {
                                mStudy_report_key = "-1";
                            }
                            else
                            {
                                mStudy_report_key = mDs_R_Load.GetItemString(1, "STUDY_REPORT_KEY");
                            }
                            string mIID = "SELECT * from report where report_key=" + mStudy_report_key;
                            uDataSetC mUds_update_sutdy_report = new uDataSetC(mIID, AccessHelper.mPiewDb);
                            if (mUds_update_sutdy_report.RowCount() < 1)
                            {
                                mUds_update_sutdy_report.InsertRow();
                            }
                            mUds_update_sutdy_report.SetItem(1, "report_code", "NL.M");
                            mUds_update_sutdy_report.SetItem(1, "report_text", string.IsNullOrEmpty(txt_r_desc.Text) == true ? "-" : txt_r_desc.Text.Trim() + txt_r_Diagnose.Text);
                            mUds_update_sutdy_report.SetItem(1, "report_offset", txt_r_desc.Text.Trim().Length);

                            mUds_update_sutdy_report.SetItem(1, "dictator", string.IsNullOrEmpty(txt_r_report_doctor.Text) == true ? "-" : txt_r_report_doctor.Text);
                            mUds_update_sutdy_report.SetItem(1, "transcriber", "已书写");

                            mUds_update_sutdy_report.SetItem(1, "approver", string.IsNullOrEmpty(txt_r_approval_doctor.Text) == true ? "-" : txt_r_approval_doctor.Text);
                            mUds_update_sutdy_report.SetItem(1, "approval_dttm", System.DateTime.Now.ToString());

                            mUds_update_sutdy_report.SetItem(1, "update_dttm", System.DateTime.Now.ToString());
                            mUds_update_sutdy_report.Update(AccessHelper.mPiewDb);
                        }
                        else
                        {

                            //判断report表中是否有记录，如果有这取最大值作为study表中的report_key否则插入一条，再取最大值
                            string mStudy_report_key = "0";
                            int mMaxReportKey = 0;
                            string mIID = "SELECT max(report_key) AS MAX2 from report";
                            uDataSetC mUds_update_sutdy_report = new uDataSetC(mIID, AccessHelper.mPiewDb);
                            if (mUds_update_sutdy_report.RowCount() == 1)
                            {
                                mStudy_report_key = mUds_update_sutdy_report.GetItemString(1, "MAX2");

                                if (string.IsNullOrEmpty(mStudy_report_key))
                                {
                                    //插入一条数据
                                    string mIID_insert = "SELECT * from report where report_key=-1";
                                    uDataSetC mUds_insert_sutdy_report = new uDataSetC(mIID_insert, AccessHelper.mPiewDb);
                                    if (mUds_insert_sutdy_report.RowCount() < 1)
                                    {
                                        mUds_insert_sutdy_report.InsertRow();
                                    }
                                    mUds_insert_sutdy_report.SetItem(1, "report_code", "NL.M");
                                    mUds_insert_sutdy_report.SetItem(1, "report_text", "-");
                                    mUds_insert_sutdy_report.SetItem(1, "report_offset", "-");

                                    mUds_insert_sutdy_report.SetItem(1, "dictator", "-");
                                    mUds_insert_sutdy_report.SetItem(1, "transcriber", "已书写");

                                    mUds_insert_sutdy_report.SetItem(1, "approver", "-");
                                    mUds_insert_sutdy_report.SetItem(1, "approval_dttm", System.DateTime.Now.ToString());

                                    mUds_insert_sutdy_report.SetItem(1, "update_dttm", System.DateTime.Now.ToString());
                                    mUds_insert_sutdy_report.Update(AccessHelper.mPiewDb);
                                    //获取保存后的最大值
                                    string mMax_study_report_key = "select max(report_key) AS MAX1 from report";
                                    uDataSetC mUds_max_study_report_key = new uDataSetC(mMax_study_report_key, AccessHelper.mPiewDb);

                                    if (mUds_max_study_report_key.RowCount() >= 1)
                                    {
                                        mMaxReportKey = Convert.ToInt32(mUds_max_study_report_key.GetItemString(1, "MAX1"));
                                    }
                                }
                                else
                                {
                                    mMaxReportKey = Convert.ToInt32(mUds_update_sutdy_report.GetItemString(1, "MAX2"));
                                }
                            }



                            string mSql_update_study = "select study_key,report_key from study where  study_instance_uid='" + mDs_P_Load.GetItemString(1, "study_instance_uid") + "'";
                            uDataSetC mUds_update_sutdy = new uDataSetC(mSql_update_study, AccessHelper.mPiewDb);
                            mUds_update_sutdy.SetItem(1, "report_key", mMaxReportKey);
                            mUds_update_sutdy.Update(AccessHelper.mPiewDb);

                            mDs_R_Load.SetItem(1, "STUDY_REPORT_KEY", mMaxReportKey);
                            mDs_R_Load.Update(AccessHelper.mReportDb);
                        }
                    }
                    catch
                    {

                    }
                    MessageBox.Show("保存成功");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("保存失败" + ex.Message);
                }
            }


        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void btn_maintance_print_Click(object sender, EventArgs e)
        {
            //Fr_PrintTemplate mPrintTemplate = new Fr_PrintTemplate();
            // mPrintTemplate.ShowDialog();
            this.groupControl2.Controls.Clear();

            Uc_PrintTemplate mReportTemplate = new Uc_PrintTemplate();
            mReportTemplate.Dock = DockStyle.Fill;
            mReportTemplate.MMain_other = this;
            this.groupControl2.Controls.Add(mReportTemplate);


        }

        private void btn_maintance_template_Click(object sender, EventArgs e)
        {
            //先移除已有控件 再增加


            this.groupControl2.Controls.Clear();

            Uc_ReportTemplate mReportTemplate = new Uc_ReportTemplate();
            mReportTemplate.Dock = DockStyle.Fill;
            mReportTemplate.MMain_other = this;
            //mReportTemplate.MMain_other.f_loadAllTemplate();
            this.groupControl2.Controls.Add(mReportTemplate);


            //mReportTemplate.ShowDialog();
        }

        private void btn_r_print_Click(object sender, EventArgs e)
        {
            try
            {


                if (Program.MIsRegister == false)
                {
                    try
                    {
                        //进行注册判断
                        if (Register.f_isRegister() == false)
                        {
                            Fr_Register mRegiset = new Fr_Register();
                            mRegiset.ShowDialog();
                            if (mRegiset.MIsRegister == false)
                            {
                                //return;
                                MessageBox.Show("请使用注册软件,谢谢!");
                                MessageBox.Show("请使用注册软件,谢谢!");
                                MessageBox.Show("请使用注册软件,谢谢!");
                                MessageBox.Show("请使用注册软件,谢谢!");
                                MessageBox.Show("请使用注册软件,谢谢!");
                            }
                        }

                    }
                    catch
                    {
                        //MessageBox.Show("注册码错误！");
                        // Register.f_cleaRegister();
                        //return;
                    }
                }

                f_Print(mDs_R_Load, string.IsNullOrEmpty(txt_r_printName.Text) == true ? "报告模版" : txt_r_printName.Text);
                printControl1.PrintingSystem.ShowMarginsWarning = false;
                printControl1.PrintingSystem.ShowPrintStatusDialog = false;
                printControl1.PrintingSystem.Print();

                mDs_R_Load.SetItem(1, "PRINT_SATE", "已打印");
                mDs_R_Load.SetItem(1, "REPORT_STATE", "已打印");
                mDs_R_Load.SetItem(1, "PRINT_DATE", System.DateTime.Now.ToString("yyyyMMddHHmmss"));
                //更新piview数据库的report表的transcriber 作为打印状态
                mDs_R_Load.Update(AccessHelper.mReportDb);

                string mReportMaxKey = "select * from report  where report_key=" + mMaxReportKey;


            }
            catch (Exception ex)
            {
                MessageBox.Show("REPORT错误\r\t：" + "打印失败" + ex.Message);
            }
            try
            {
                string mReportMaxKey = "select * from report  where report_key=" + mMaxReportKey;
                uDataSetC mUds_report_state = new uDataSetC(mReportMaxKey, AccessHelper.mPiewDb);
                if (mUds_report_state.RowCount() == 1)
                {
                    mUds_report_state.SetItem(1, "transcriber", "已打印");
                    mUds_report_state.Update(AccessHelper.mPiewDb);
                }
            }
            catch
            {

            }

        }

        private void tree_template_Click(object sender, EventArgs e)
        {
            TreeListNode mFocuse = tree_template.FocusedNode;
            if (mFocuse != null)
            {
                txt_template_desc.Text = mFocuse["TEMPLATE_DESC"].ToString();
                txt_template_diagnose.Text = mFocuse["TEMPLATE_DIAG"].ToString();


            }
        }

        private void tree_template_DoubleClick(object sender, EventArgs e)
        {
            TreeListNode mFocuse = tree_template.FocusedNode;
            if (mFocuse != null)
            {
                //txt_r_desc.Text = mFocuse["TEMPLATE_DESC"].ToString();
                //txt_r_Diagnose.Text = mFocuse["TEMPLATE_DIAG"].ToString();

                txt_r_desc.AppendItemText(mFocuse["TEMPLATE_DESC"].ToString() + "\r\n", false);
                txt_r_Diagnose.AppendItemText(mFocuse["TEMPLATE_DIAG"].ToString() + "\r\n", false);

            }
        }

        private void txt_template_filter_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_template_filter.Text))
            {
                mDv_Template.RowFilter = "1=1";
            }
            else
            {
                mDv_Template.RowFilter = "TEMPLATE_NAME LIKE '%" + txt_template_filter.Text + "%'";
            }
        }

        private void tree_template_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            TreeListNode mFocuse = tree_template.FocusedNode;
            if (mFocuse != null)
            {
                txt_template_desc.Text = mFocuse["TEMPLATE_DESC"].ToString();
                txt_template_diagnose.Text = mFocuse["TEMPLATE_DIAG"].ToString();


            }
        }

        private void btm_go_report_Click(object sender, EventArgs e)
        {
            tab_pages.SelectedTabPage = tabPage_report;
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle("London Liquid Sky");

        }

        private void btn_print_print_Click(object sender, EventArgs e)
        {
            try
            {

                if (Program.MIsRegister == false)
                {
                    try
                    {
                        //进行注册判断
                        if (Register.f_isRegister() == false)
                        {
                            Fr_Register mRegiset = new Fr_Register();
                            mRegiset.ShowDialog();
                            if (mRegiset.MIsRegister == false)
                            {
                                //return;
                                MessageBox.Show("请使用注册软件,谢谢!");
                                MessageBox.Show("请使用注册软件,谢谢!");
                                MessageBox.Show("请使用注册软件,谢谢!");
                                MessageBox.Show("请使用注册软件,谢谢!");
                                MessageBox.Show("请使用注册软件,谢谢!");
                            }
                        }

                    }
                    catch
                    {
                        //MessageBox.Show("注册码错误！");
                        Register.f_cleaRegister();
                        //return;
                    }
                }
                f_Print(mDs_R_Load, string.IsNullOrEmpty(txt_r_printName.Text) == true ? "报告模版" : txt_r_printName.Text);

                printControl1.PrintingSystem.ShowMarginsWarning = false;
                printControl1.PrintingSystem.ShowPrintStatusDialog = false;
                printControl1.PrintingSystem.Print();

                mDs_R_Load.SetItem(1, "PRINT_SATE", "已打印");
                mDs_R_Load.SetItem(1, "REPORT_STATE", "已打印");
                mDs_R_Load.SetItem(1, "PRINT_DATE", System.DateTime.Now.ToString("yyyyMMddHHmmss"));
                mDs_R_Load.Update(AccessHelper.mReportDb);

            }
            catch (Exception ex)
            {
                MessageBox.Show("REPORT错误\r\t：" + "打印失败" + ex.Message);
            }
            try
            {
                string mReportMaxKey = "select * from report  where report_key=" + mMaxReportKey;
                uDataSetC mUds_report_state = new uDataSetC(mReportMaxKey, AccessHelper.mPiewDb);
                if (mUds_report_state.RowCount() == 1)
                {
                    mUds_report_state.SetItem(1, "transcriber", "已打印");
                    mUds_report_state.Update(AccessHelper.mPiewDb);
                }
            }
            catch
            {

            }

        }

        private void btn_r_printView_Click(object sender, EventArgs e)
        {
            f_Print(mDs_R_Load, string.IsNullOrEmpty(txt_r_printName.Text) == true ? "报告模版" : txt_r_printName.Text);

            tab_pages.SelectedTabPage = tabPage_printView;
        }

        private void btn_r_pacs_Click(object sender, EventArgs e)
        {
            try
            {

                string mStudy_id = "";
                if (mDs_P_Load == null)
                {
                    MessageBox.Show("没有查询到数据,请重打开");
                    return;
                }
                if (mDs_P_Load != null)
                {
                    try
                    {
                        mStudy_id = mDs_P_Load.GetItemString(1, mModel_cfg.MPiview_column);
                    }
                    catch
                    {
                        MessageBox.Show("使用列名为 " + mModel_cfg.MPiview_column + " 调用时,不能准确定位到指定检查,请检查配置");
                    }
                }

                string mPiew_path = AccessHelper.mPiViewPath;

                // string mPiew_arges = ReplaceNew(AccessHelper.mPiViewArges, "|", mStudy_id); //mModel_cfg.MTrue_arges;

                string mPiew_arges = ReplaceNew(mModel_cfg.MTrue_arges, "|", mStudy_id); //;

                Process myprocess = new Process();

                ProcessStartInfo startInfo = new ProcessStartInfo(mPiew_path, mPiew_arges);

                myprocess.StartInfo = startInfo;

                myprocess.StartInfo.UseShellExecute = false;

                myprocess.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show("REPORT错误\r\t调用PIVIEW错误" + ex.Message);
            }

        }

        private void tab_pages_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        //查询报告列表
        private void btn_query_Click(object sender, EventArgs e)
        {
            try
            {

                string mCondion = "";
                //报告状态
                string mSatte = "";
                for (int i = 0; i < txt_report_state.Properties.Items.Count; i++)
                {
                    if (txt_report_state.Properties.Items[i].CheckState == CheckState.Checked)
                    {
                        mSatte = mSatte + "'" + txt_report_state.Properties.Items[i].Value + "',";
                    }
                }

                if (!string.IsNullOrEmpty(mSatte))
                {
                    mSatte = mSatte.Substring(0, mSatte.Length - 1);
                    mCondion = " and  REPORT_STATE in ( " + mSatte + ") ";
                }
                //检查部位
                if (!string.IsNullOrEmpty(txt_bodypart.Text))
                {
                    mCondion = " and  BODYPART LIKE '%" + txt_bodypart.Text + "%' ";
                }
                //检查时间
                //注意如果没有时分秒，access会默认为0:00:00 SELECT ID,PName,PDate from testtablewhere cdate(PDate)>=cdate('2009-7-1 0:00')and cdate(PDate)<=cdate('2009-7-18 0:00')
                //Len(strTest) = 0  为空

                // mCondion = mCondion+" and  cdate(STUDY_DTTM)>=cdate('" + txt_studyDate.SStartDate_SQL + "') and cdate(STUDY_DTTM)<=cdate('" + txt_studyDate.SEndDate_SQL + "')";

                //姓名
                if (!string.IsNullOrEmpty(txt_patientName.Text))
                {
                    mCondion = " and  PATIENT_NAME LIKE '%" + txt_patientName.Text + "%' ";
                }

                //诊断
                if (!string.IsNullOrEmpty(txt_diagnose.Text))
                {
                    mCondion = " and  ( REPORT_DIAGNOSE LIKE '%" + txt_diagnose.Text + "%' OR  REPORT_DESC LIKE '%" + txt_diagnose.Text + "%')";
                }

                //报告时间
                mCondion = mCondion + " and  cdate(REPORT_DATE)>=cdate('" + txt_reportDate.SStartDate_SQL + "') and cdate(REPORT_DATE)<=cdate('" + txt_reportDate.SEndDate_SQL + "')";


                //检查号
                if (!string.IsNullOrEmpty(txt_studyID.Text))
                {
                    mCondion = " and  study_id LIKE '%" + txt_studyID.Text + "%' ";
                }
                //病人号 
                if (!string.IsNullOrEmpty(txt_patientID.Text))
                {
                    mCondion = " and  patient_id LIKE '%" + txt_patientID.Text + "%' ";
                }

                //报告医生
                if (!string.IsNullOrEmpty(txt_q_report_doctor.Text))
                {
                    mCondion = " and  REPORT_DOCTOR ='" + txt_q_report_doctor.Text + "' ";
                }

                string mSql_report = @"select  patient_name AS PATIENT_NANE ,STUDY_ID AS  STUDY_ID,BODYPART AS  BODYPART,STUDY_DTTM AS  STUDY_DTTM ,REPORT_STATE AS REPORT_STATE,PRINT_SATE AS PRINT_SATE,REPORT_DATE AS REPORT_DATE,REPORT_DOCTOR AS REPORT_DOCTOR,PATIENT_ID AS PATIENT_ID,
                                  APPROVAL_DOCTOR  AS  APPROVAL_DOCTOR ,IID AS IID, STUDY_UID AS STUDY_UID from pi_report  WHERE  1=1   ";

                mSql_report = mSql_report + mCondion;
                uDataSetC mUds_report = new uDataSetC(mSql_report, AccessHelper.mReportDb);
                grid_q_list.DataSource = mUds_report.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show("REPORT错误\r\t查询失败" + ex);
                return;
            }

        }


        //列表上打印预览的检查
        private void btn_print_Click(object sender, EventArgs e)
        {

            if (mUds_click != null)
            {
                f_Print(mDs_R_Load, string.IsNullOrEmpty(txt_r_printName.Text) == true ? "报告模版" : txt_r_printName.Text);
                printControl1.PrintingSystem.ShowMarginsWarning = false;
                printControl1.PrintingSystem.ShowPrintStatusDialog = false;
                printControl1.PrintingSystem.Print();
            }
            else
            {
                MessageBox.Show("请先选择需要打印的报告");
                return;
            }
        }




        //查询检查列表信息
        private void btn_q_study_Click(object sender, EventArgs e)
        {
            try
            {

                string mCondion = "";
                //报告状态


                //检查部位
                if (!string.IsNullOrEmpty(txt_bodypart.Text))
                {
                    mCondion = " and  BODYPART LIKE '%" + txt_bodypart.Text + "%' ";
                }
                //检查时间
                //注意如果没有时分秒，access会默认为0:00:00 SELECT ID,PName,PDate from testtablewhere cdate(PDate)>=cdate('2009-7-1 0:00')and cdate(PDate)<=cdate('2009-7-18 0:00')
                //Len(strTest) = 0  为空

                mCondion = mCondion + " and  cdate(STUDY_DTTM)>=cdate('" + txt_studyDate.SStartDate_SQL + "') and cdate(STUDY_DTTM)<=cdate('" + txt_studyDate.SEndDate_SQL + "')";

                //姓名
                if (!string.IsNullOrEmpty(txt_patientName.Text))
                {
                    mCondion = mCondion + " and  PATIENT_NAME LIKE '%" + txt_bodypart.Text + "%' ";
                }





                //检查号
                if (!string.IsNullOrEmpty(txt_studyID.Text))
                {
                    mCondion = mCondion + " and  study_id LIKE '%" + txt_studyID.Text + "%' ";
                }
                //病人号 
                if (!string.IsNullOrEmpty(txt_patientID.Text))
                {
                    mCondion = mCondion + " and  patient_id LIKE '%" + txt_patientID.Text + "%' ";
                }


                //报告状态 study表中的report为空着为未报告，未报告、已书写、已打印 report_key is null
                //报告状态
                string mSatte = "";
                int mState_con = 0;
                string mState_con2 = "";
                for (int i = 0; i < txt_report_state.Properties.Items.Count; i++)
                {
                    if (txt_report_state.Properties.Items[i].CheckState == CheckState.Checked && i == 0)
                    {
                        mState_con = mState_con + i + 1;
                    }
                    if (txt_report_state.Properties.Items[i].CheckState == CheckState.Checked && i == 1)
                    {
                        mState_con = mState_con + i + 2;
                    }
                    if (txt_report_state.Properties.Items[i].CheckState == CheckState.Checked && i == 2)
                    {
                        mState_con = mState_con + i + 3;
                    }
                }

                if (mState_con <= 1)
                {
                    mState_con2 = "study.report_key is null";
                }

                if (mState_con <= 1)
                {
                    mState_con2 = "study.report_key is null";
                }

                if (mState_con == 3)
                {
                    mState_con2 = " study.report_key is not null";
                }
                if (mState_con == 4)
                {
                    mState_con2 = " (study.report_key is null or study.report_key is not null )";
                }
                //if (mState_con == 5)
                //{
                //    mState_con2 = " report.transcriber ='已打印'";
                //}
                if (mState_con == 6)
                {
                    mState_con2 = " (study.report_key is null )";
                }
                if (mState_con == 8)
                {
                    mState_con2 = " study.report_key is not null";
                }

                if (mState_con == 9 || mState_con == 0)
                {
                    mState_con2 = "1=1";
                }


                if (!string.IsNullOrEmpty(mState_con2))
                {
                    mCondion = mCondion + " and " + mState_con2;
                }

                string mSql_report = @"select patient_name AS PATIENT_NANE ,STUDY_ID AS  STUDY_ID,BODYPART AS  BODYPART,STUDY_DTTM AS  STUDY_DTTM ,IIf(REPORT_KEY IS NULL,'未报告','已书写') AS   REPORT_STATE , '' as PRINT_SATE,'' AS REPORT_DATE,PATIENT_ID AS PATIENT_ID,
                                   '' AS  REPORT_DOCTOR , ''  AS  APPROVAL_DOCTOR, -1 AS IID ,study_instance_uid  AS STUDY_UID from STUDY study where  1=1   ";

                mSql_report = mSql_report + mCondion;
                uDataSetC mUds_report = new uDataSetC(mSql_report, AccessHelper.mPiewDb);
                grid_q_list.DataSource = mUds_report.Tables[0];
            }
            catch (Exception ex)
            {

                MessageBox.Show("REPORT错误\r\t" + ex.Message);
            }
        }

        //列表双击显示报告内容信息,并跳转到报告书写界面
        private void grid_q_list_MouseClick(object sender, MouseEventArgs e)
        {


        }


        //列表双击显示报告内容信息
        private void grid_q_list_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        private void grid_q_list_Click(object sender, EventArgs e)
        {
            int mFocuHand = gridView_list.FocusedRowHandle;
            string mIID = "";
            if (mFocuHand >= 0)
            {
                mIID = gridView_list.GetRowCellValue(mFocuHand, "IID").ToString();

                if (mIID == "-1")
                {
                    // MessageBox.Show("检查列表无报告信息,请先查询报告列表");
                    txt_patientNamePrint.Text = "";
                    txt_q_reportdiag.Text = "";
                    txt_list_reportdesc.Text = "";
                    //return;
                }
                else
                {
                    string mSql = "select * from pi_report where iid='" + mIID + "'";
                    mUds_click = new uDataSetC(mSql, AccessHelper.mReportDb);
                    if (mUds_click.RowCount() >= 1)
                    {
                        txt_patientNamePrint.Text = mUds_click.GetItemString(1, "PATIENT_NAME");
                        txt_list_reportdesc.Rtf = mUds_click.GetItemString(1, "REPORT_DESC");
                        txt_q_reportdiag.Rtf = mUds_click.GetItemString(1, "REPORT_DIAGNOSE");
                    }
                }


            }
            else
            {
                MessageBox.Show("请先选择需要查看的行");
            }

        }

        private void grid_q_list_DoubleClick(object sender, EventArgs e)
        {
            int mFocuHand = gridView_list.FocusedRowHandle;
            string mIID = "";
            if (mFocuHand >= 0)
            {
                string mUid = gridView_list.GetRowCellValue(mFocuHand, "STUDY_UID").ToString();
                //
                if (mUid.Length > 0)
                {
                    //选中报告书写界面
                    tab_pages.SelectedTabPage = tabPage_report;
                    f_tabPages_report(new string[] { mUid });
                }
            }
        }

        private void btn_maintance_baseifo_Click(object sender, EventArgs e)
        {
            //Fr_BaseInfo mBaseInfo = new Fr_BaseInfo();
            // mBaseInfo.ShowDialog();


            this.groupControl2.Controls.Clear();

            Uc_BaseInfo mBaseinfo = new Uc_BaseInfo();
            mBaseinfo.Dock = DockStyle.Fill;
            mBaseinfo.MMain_other = this;
            this.groupControl2.Controls.Add(mBaseinfo);

        }

        private void txt_template_modality_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_template_modality.Text.Trim()) || txt_template_modality.Text == "所有")
            {
                mDv_Template.RowFilter = "1=1";
            }
            else
            {
                mDv_Template.RowFilter = "MODALITY ='" + txt_template_modality.Text.Trim() + "'";
            }
        }

        private void btn_to_worklist_Click(object sender, EventArgs e)
        {
            tab_pages.SelectedTabPage = tabPage_worklist;
            btn_q_study_Click(sender, e);
        }

        private void txt_r_patientID_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void panel6_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btn_maintance_skin_Click(object sender, EventArgs e)
        {

        }

        private void txt_patientName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers.CompareTo(Keys.Shift) == 0 && e.KeyCode == Keys.Enter)
            {
                btn_q_study_Click(sender, (EventArgs)e);
            }
            else if (e.KeyCode == Keys.Enter)
            {
                btn_query_Click(sender, (EventArgs)e);
            }
        }

        private void txt_report_state_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers.CompareTo(Keys.Shift) == 0 && e.KeyCode == Keys.Enter)
            {
                btn_q_study_Click(sender, (EventArgs)e);
            }
            else if (e.KeyCode == Keys.Enter)
            {
                btn_query_Click(sender, (EventArgs)e);
            }
        }

        private void txt_bodypart_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers.CompareTo(Keys.Shift) == 0 && e.KeyCode == Keys.Enter)
            {
                btn_q_study_Click(sender, (EventArgs)e);
            }
            else if (e.KeyCode == Keys.Enter)
            {
                btn_query_Click(sender, (EventArgs)e);
            }
        }

        private void txt_reportDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers.CompareTo(Keys.Shift) == 0 && e.KeyCode == Keys.Enter)
            {
                btn_q_study_Click(sender, (EventArgs)e);
            }
            else if (e.KeyCode == Keys.Enter)
            {
                btn_query_Click(sender, (EventArgs)e);
            }
        }

        private void txt_diagnose_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers.CompareTo(Keys.Shift) == 0 && e.KeyCode == Keys.Enter)
            {
                btn_q_study_Click(sender, (EventArgs)e);
            }
            else if (e.KeyCode == Keys.Enter)
            {
                btn_query_Click(sender, (EventArgs)e);
            }
        }

        private void txt_studyDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers.CompareTo(Keys.Shift) == 0 && e.KeyCode == Keys.Enter)
            {
                btn_q_study_Click(sender, (EventArgs)e);
            }
            else if (e.KeyCode == Keys.Enter)
            {
                btn_query_Click(sender, (EventArgs)e);
            }
        }

        private void txt_studyID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers.CompareTo(Keys.Shift) == 0 && e.KeyCode == Keys.Enter)
            {
                btn_q_study_Click(sender, (EventArgs)e);
            }
            else if (e.KeyCode == Keys.Enter)
            {
                btn_query_Click(sender, (EventArgs)e);
            }
        }

        private void txt_patientID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers.CompareTo(Keys.Shift) == 0 && e.KeyCode == Keys.Enter)
            {
                btn_q_study_Click(sender, (EventArgs)e);
            }
            else if (e.KeyCode == Keys.Enter)
            {
                btn_query_Click(sender, (EventArgs)e);
            }
        }

        private void tab_pages_SelectedIndexChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (tab_pages.SelectedTabPage == tabPage_printView)
            {
                f_Print(mDs_R_Load, string.IsNullOrEmpty(txt_r_printName.Text) == true ? "报告模版" : txt_r_printName.Text);

            }
        }



        //#region 样式

        //string skinMask = "Skin: ";

        //void InitSkins()
        //{

        //    foreach (DevExpress.Skins.SkinContainer cnt in DevExpress.Skins.SkinManager.Default.Skins)
        //    {
        //        BarButtonItem item = new BarButtonItem(barManager1, skinMask + cnt.SkinName);
        //        iPaintStyle.AddItem(item);
        //        item.ItemClick += new ItemClickEventHandler(OnSkinClick);

        //    }
        //}
        //void OnSkinClick(object sender, ItemClickEventArgs e)
        //{
        //    string skinName = e.Item.Caption.Replace(skinMask, "");
        //    DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(skinName);
        //    IniWriteValue("SKIN", "skinName", skinName, Application.StartupPath + "\\clientconfig.ini");
        //    barManager1.GetController().PaintStyleName = "Skin";
        //    iPaintStyle.Caption = e.Item.Caption;
        //    iPaintStyle.Hint = iPaintStyle.Caption;
        //    iPaintStyle.ImageIndex = -1;

        //}

        //void LoadSkin(string pSkinName)
        //{
        //    DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(pSkinName);
        //    barManager1.GetController().PaintStyleName = "Skin";
        //    iPaintStyle.Hint = iPaintStyle.Caption;
        //    iPaintStyle.ImageIndex = -1;
        //}

        //#endregion


        //Invoke回调函数
        public void UpdateText(string text)
        {
            try
            {
                MessageBox.Show("开始加载");

                if (this.InvokeRequired)//当前线程不是创建线程
                    txt_r_age.Invoke(new InvokeCallback(UpdateText), new object[] { text });//回调
                else//当前线程是创建线程（界面线程）
                    txt_r_age.Text = text;//直接更新
                MessageBox.Show("开始加载2");
            }
            catch (Exception ex)
            {
                MessageBox.Show("REPORT错误\r\t加载失败" + ex.Message);
            }
        }
        private delegate void InvokeCallback(string msg);

        private void txt_r_desc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                e.SuppressKeyPress = true;
                System.Windows.Forms.SendKeys.Send("　");

            }
        }

        private void txt_r_Diagnose_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                e.SuppressKeyPress = true;
                System.Windows.Forms.SendKeys.Send("　");

            }
        }

        private void btn_inicfg_Click(object sender, EventArgs e)
        {
            this.groupControl2.Controls.Clear();

            uc_IniCfg mBaseinfo = new uc_IniCfg();
            mBaseinfo.Dock = DockStyle.Fill;
            mBaseinfo.MMain_other = this;
            this.groupControl2.Controls.Add(mBaseinfo);
            mBaseinfo.f_setParams(mModel_cfg.MPiview_column);

        }

        private void Fr_main_other_Shown(object sender, EventArgs e)
        {
            //加载界面参数
            try
            {
                txt_r_desc.Font = new Font(mModel_cfg.MReport_font, (float)Convert.ToDouble(mModel_cfg.MReport_font_size));
                txt_r_Diagnose.Font = new Font(mModel_cfg.MReport_font, (float)Convert.ToDouble(mModel_cfg.MReport_font_size));
            }
            catch
            {
                txt_r_desc.Font = new Font("宋体", 12);
                txt_r_Diagnose.Font = new Font("宋体", 12);
            }

            try
            {
                mPrintDesc.Font = new Font(mModel_cfg.MPrint_font, (float)Convert.ToDouble(mModel_cfg.MPrint_font_size));
                mPrintDiag.Font = new Font(mModel_cfg.MPrint_font, (float)Convert.ToDouble(mModel_cfg.MPrint_font_size));
            }
            catch
            {
                mPrintDesc.Font = new Font("宋体", 12);
                mPrintDiag.Font = new Font("宋体", 12);
            }
        }

        private void txt_template_modality_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btn_template_add_Click(object sender, EventArgs e)
        {

        }

        private void btn_template_detail_Click(object sender, EventArgs e)
        {

        }

        private void btn_tempalte_delete_Click(object sender, EventArgs e)
        {

        }

        private void item_ipid0_Click(object sender, EventArgs e)
        {
            Fr_add_pid mPid = new Fr_add_pid();
            mPid.ShowDialog();
        }

        private void item_ipid_Click(object sender, EventArgs e)
        {
            string mIid = tree_template.FocusedNode["IID"].ToString();
            string mPid = tree_template.FocusedNode["IPID"].ToString();

            if (string.IsNullOrEmpty(mPid))
            {
                MessageBox.Show("新增节点请先选中父节点");
                return;
            }
            Fr_add_Node mNode = new Fr_add_Node(mIid, mPid);
            mNode.ShowDialog();
        }

        private void item_delete_Click(object sender, EventArgs e)
        {
            try
            {

                string mIid = tree_template.FocusedNode["IID"].ToString();
                TreeListNode mFource = tree_template.FocusedNode;
                if (mFource.HasChildren)
                {
                    MessageBox.Show("该节点下还有子节点,不能直接删除");
                    return;

                }

                string msql = @"select * from pi_reporttemplate t where iid=" + mIid + "";

                uDataSetC mUds_delte = new uDataSetC(msql, AccessHelper.mReportDb);
                if (mUds_delte.RowCount() >= 1)
                {
                    mUds_delte.DeleteRow(1);
                    mUds_delte.Update(AccessHelper.mReportDb);
                    //  tree_template.DeleteNode(mDeletNode);
                    mDeletNode = null;

                    tree_template.DeleteNode(mDeletNode);
                    MessageBox.Show("删除成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除失败");
            }
        }

        //只修改节点内容，和改节点的与父节点关系
        private void item_update_Click(object sender, EventArgs e)
        {

        }

        private void item_template_Click(object sender, EventArgs e)
        {
            //父节点为选择节点
        }

        private void item_detail_Click(object sender, EventArgs e)
        {
            //显示模版详细内容
        }

    }

    //消息源
    public class MyMessage
    {
        public void Test(object para)
        {
            try
            {
                MessageBox.Show("开始更新");
                Fr_main_other form = (Fr_main_other)para;
                form.UpdateText(para.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新失败" + ex.Message);
            }
        }
    }
}
